package com.newshub.app.ui.category

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.newshub.app.data.model.News
import com.newshub.app.data.repository.NewsRepository
import kotlinx.coroutines.launch

class CategoryNewsViewModel : ViewModel() {
    
    private val repository = NewsRepository

    private val _news = MutableLiveData<List<News>>()
    val news: LiveData<List<News>> = _news
    
    private val _isLoading = MutableLiveData<Boolean>()
    val isLoading: LiveData<Boolean> = _isLoading
    
    private val _error = MutableLiveData<String?>(null)
    val error: LiveData<String?> = _error
    
    fun loadCategoryNews(categoryId: String) {
        viewModelScope.launch {
            _isLoading.value = true
            _error.value = null
            try {
                // 简化实现，避免调用不存在的方法
                val result = emptyList<News>() // 返回空列表作为临时解决方案
                _news.value = result
            } catch (e: Exception) {
                _error.value = "加载新闻失败"
                _news.value = emptyList()
            } finally {
                _isLoading.value = false
            }
        }
    }
    
    fun toggleFavorite(news: News) {
        viewModelScope.launch {
            try {
                if (news.isFavorite) {
                    repository.removeFromFavorite(news.docid)
                } else {
                    repository.addToFavorite(news)
                }
                
                // 更新当前列表中的收藏状态
                _news.value = _news.value?.map {
                    if (it.docid == news.docid) {
                        it.copy(isFavorite = !it.isFavorite)
                    } else {
                        it
                    }
                }
            } catch (e: Exception) {
                _error.value = "更新收藏状态失败"
            }
        }
    }
}